package com.heima.search.linstener;

import com.heima.common.constants.message.Article2EsConstants;
import com.heima.common.constants.message.WmNewsUpDownConstants;
import com.heima.common.util.JsonUtils;
import com.heima.model.media.dtos.WmNewsDownOrUpDTO;
import com.heima.search.service.ApArticleSearchService;
import lombok.extern.slf4j.Slf4j;
import org.apache.kafka.clients.consumer.ConsumerRecord;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.kafka.annotation.KafkaListener;
import org.springframework.stereotype.Component;

/**
 * @author Fuqiang
 * @since :2023-03-31
 */
@Slf4j
@Component
public class ApArticleListener {

    @Autowired
    ApArticleSearchService apArticleSearchService;

    /**
     * 监听article文章新增
     *
     * @param record
     */
    @KafkaListener(topics = Article2EsConstants.ARTICLE_2_ES_TOPIC)
    public void onMessage(ConsumerRecord<String, String> record) {

        if (record == null) {
            return;
        }
        String articleId = record.value();
        log.info("监听到article新增,开始进行es增量同步.... articleId = {}", articleId);

        apArticleSearchService.onArticleCreate(Long.valueOf(articleId));
    }

    /**
     * 监听文章上下架
     *
     * @param record
     */
    @KafkaListener(topics = WmNewsUpDownConstants.WM_NEWS_UP_OR_DOWN_TOPIC)
    public void onArticleUpOrDown(ConsumerRecord<String, String> record) {
        if (record == null) {
            return;
        }
        String wmNewsDownOrUpDtoJson = record.value();
        WmNewsDownOrUpDTO dto = JsonUtils.toBean(wmNewsDownOrUpDtoJson, WmNewsDownOrUpDTO.class);
        if (dto != null) {
            log.info("监听到article上下架,开始进行es增量同步.... articleId = {}", dto.getArticleId());
            apArticleSearchService.onArticleUpOrDown(dto);
        }
    }
}
